package com.tomtop.core.code;

import java.util.LinkedList;

public class TransforCode {

	private final byte[] bytes;

	private final int length;

	public TransforCode(byte[] bytes) {
		this.length = bytes.length;
		this.bytes = bytes;
	}

	public TransforCode(byte length) {
		byte len = (byte) (length / 2);
		byte[] bytes = new byte[length];
		for (byte i = 0; i < length; i++) {
			bytes[i] = (byte) (i - len);
		}
		this.length = bytes.length;
		this.bytes = bytes;
	}

	public byte[] serialize(Long len) {
		if (len == null)
			return null;
		LinkedList<Byte> list = new LinkedList<>();
		do {
			list.add(bytes[(int) (len % length)]);
		} while ((len = len / length) != 0);
		byte[] bytes = new byte[list.size()];
		for (int i = bytes.length - 1; i >= 0; i--) {
			bytes[i] = list.get(i);
		}
		return bytes;
	}

	public Long deserialize(byte[] _bytes) {
		if (_bytes == null)
			return null;
		long lval = 0;
		for (byte _byte : _bytes) {
			for (int i = 0; i < bytes.length; i++) {
				if (bytes[i] == _byte) {
					lval = lval * length + i;
					break;
				}
			}
		}
		return lval;
	}

	private final static TransforCode CODE_256 = new TransforCode((byte) 256);

	public static final byte[] serialize256(Long len) {
		return CODE_256.serialize(len);
	}

	public static final Long deserialize256(byte[] bytes) {
		return CODE_256.deserialize(bytes);
	}
}
